package com.common.library.ui.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.common.library.R;
import com.common.library.net.HttpException;
import com.common.library.net.HttpQueue;
import com.common.library.net.HttpResponse;
import com.common.library.tools.JSONTools;
import com.common.library.ui.view.adapter.base.BaseRecyclerAdapter;
import com.common.library.ui.view.ptr.PtrDefaultLayout;
import com.google.gson.JsonElement;
import com.yolanda.nohttp.error.NetworkError;
import com.yolanda.nohttp.error.TimeoutError;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONObject;

import java.util.List;

import static com.yolanda.nohttp.NoHttp.getContext;

/**
 * @author txf
 * @Title Activity 基类
 * @package com.txf.prevention.ui.activity
 * @date 2017/5/6 0006
 */
public abstract class BaseRecyclerActivity<T> extends BaseActivity implements View.OnClickListener, OnResponseListener<JSONObject> {
    protected String TAG = getClass().getName();
    private View mBack;
    private TextView mTitle;
    private PtrDefaultLayout mPtrLayout;
    private RecyclerView mRecyclerView;
    private RecyclerAdapterWithHF mRecyclerAdapterWithHF;

    protected int pageIndex = 1;//页码
    protected int pageSize = 20;//每页条数
    protected long pageTime;// onResume 页面上次刷新时间
    protected long pageRefreshInterval = 3600000;// onResume 页面刷新间隔(一个小时)
    private BaseRecyclerAdapter<T> mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_recycler);
        getIntentData();
        initViews();
        initListener();
        init();
        init2();
    }

    private void initListener() {
        mBack.setOnClickListener(this);
    }

    private void initViews() {
        mBack = findViewById(R.id.activity_base_back);
        mTitle = (TextView) findViewById(R.id.activity_base_tv);
        mPtrLayout = (PtrDefaultLayout) findViewById(R.id.activity_base_recycler_PtrDefaultLayout);
        mRecyclerView = (RecyclerView) findViewById(R.id.activity_base_recycler_RecyclerView);
    }

    public void setTitle(String txt) {
        mTitle.setText(txt);
    }

    private void init() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerAdapterWithHF = new RecyclerAdapterWithHF(mAdapter = buildAdapter());
        mRecyclerView.setAdapter(mRecyclerAdapterWithHF);
        //默认关闭上拉加载
        mPtrLayout.setLoadMoreEnable(false);
        //水平移动时禁用
        mPtrLayout.disableWhenHorizontalMove(true);
        //下拉监听
        mPtrLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mPtrLayout.setLoadMoreEnable(false);
                pageIndex = 1;
                request(pageIndex);
            }
        });
        //上拉监听
        mPtrLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                pageIndex++;
                request(pageIndex);
            }
        });

    }

    //获取页面跳转 Intent传递过来的数据
    protected abstract void getIntentData();

    //
    protected abstract void init2();

    //网络请求
    protected abstract void request(int pageIndex);

    //构建Adapter
    protected abstract BaseRecyclerAdapter<T> buildAdapter();

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.activity_base_back){
            finish();
        }
    }

    public void refreshData(List<T> datas) {
        if (pageIndex == 1) {
            mPtrLayout.refreshComplete();
            if (datas != null && datas.size() > 0) {
                mAdapter.setDatas(datas);
                mAdapter.notifyDataSetChanged();
            }
        } else {
            mPtrLayout.loadMoreComplete(true);
            if (datas != null && datas.size() > 0){
                mAdapter.addDatas(datas);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (System.currentTimeMillis() - pageTime > pageRefreshInterval) {
            pageTime = System.currentTimeMillis();
            mPtrLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //自动刷新
                    mPtrLayout.autoRefresh();
                }
            }, 100);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        //页面关闭时，取消请求及相关动画
        HttpQueue.newHttpQueue().cancelRequest(TAG);
        if (mPtrLayout.isRefreshing()) {
            mPtrLayout.refreshComplete();
        } else if (mPtrLayout.isLoadingMore()) {
            mPtrLayout.loadMoreComplete(true);
        }
    }

    public PtrDefaultLayout getmPtrLayout() {
        return mPtrLayout;
    }
    /////////////////////////////////////////////////////////////////////
    //////////////////////////////网络请求回执///////////////////////////
    /////////////////////////////////////////////////////////////////////
    @Override
    public void onStart(int what) {
    }
    @Deprecated
    @Override
    public void onSucceed(int what, Response<JSONObject> response) {
        Log.i(TAG, "--->UN 请求结果数据:");
        Log.i(TAG, response.get().toString());
        String strDecode = response.get().toString();
        HttpResponse result = JSONTools.fromJson(strDecode, HttpResponse.class);
        //无效数据过滤掉。
        if (result == null) {
            onError(what, HttpException.NONE_RESULT.getCode(), HttpException.NONE_RESULT.getMessage());
            return;
        }
        //服务器返回的错误信息在2000以后
        int error = Integer.parseInt(result.getErrCode());
        if (error != 0) {
            onError(what, error, result.getMsg());
            return;
        }
        JsonElement data = result.getData();
        if (data == null || data.isJsonNull()) {
            onError(what, error, result.getMsg());
            return;
        }
        onSuccess(what, data, result.getMsg());
    }
    /**
     * 错误响应时
     *
     * @param what     多个请求时。该字段用于区别
     * @param response failure callback.
     */
    @Deprecated
    @Override
    public void onFailed(int what, Response<JSONObject> response) {
        response.getException().printStackTrace();
        if (response.getException() instanceof TimeoutError) {
            onError(what, HttpException.DEFAULT.getCode(), "请求超时");
        } else if (response.getException() instanceof NetworkError) {
            onError(what, HttpException.DEFAULT.getCode(), "网络异常");
        } else {
            onError(what, HttpException.DEFAULT.getCode(), HttpException.NONE_RESULT.getMessage());
        }
    }
    public void onSuccess(int what, JsonElement data, String message) {
    }
    public void onError(int what, int error, String message) {
    }
    @Override
    public void onFinish(int what) {

    }
}
